/*
 *
 *    Copyright (c) 2023 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package matter.controller.cluster.structs

import java.util.Optional
import matter.controller.cluster.*
import matter.tlv.AnonymousTag
import matter.tlv.ContextSpecificTag
import matter.tlv.Tag
import matter.tlv.TlvReader
import matter.tlv.TlvWriter

class TlsCertificateManagementClusterTLSClientCertificateDetailStruct(
  val ccdid: UShort,
  val clientCertificate: Optional<ByteArray>?,
  val intermediateCertificates: Optional<List<ByteArray>>,
  val fabricIndex: UByte,
) {
  override fun toString(): String = buildString {
    append("TlsCertificateManagementClusterTLSClientCertificateDetailStruct {\n")
    append("\tccdid : $ccdid\n")
    append("\tclientCertificate : $clientCertificate\n")
    append("\tintermediateCertificates : $intermediateCertificates\n")
    append("\tfabricIndex : $fabricIndex\n")
    append("}\n")
  }

  fun toTlv(tlvTag: Tag, tlvWriter: TlvWriter) {
    tlvWriter.apply {
      startStructure(tlvTag)
      put(ContextSpecificTag(TAG_CCDID), ccdid)
      if (clientCertificate != null) {
        if (clientCertificate.isPresent) {
          val optclientCertificate = clientCertificate.get()
          put(ContextSpecificTag(TAG_CLIENT_CERTIFICATE), optclientCertificate)
        }
      } else {
        putNull(ContextSpecificTag(TAG_CLIENT_CERTIFICATE))
      }
      if (intermediateCertificates.isPresent) {
        val optintermediateCertificates = intermediateCertificates.get()
        startArray(ContextSpecificTag(TAG_INTERMEDIATE_CERTIFICATES))
        for (item in optintermediateCertificates.iterator()) {
          put(AnonymousTag, item)
        }
        endArray()
      }
      put(ContextSpecificTag(TAG_FABRIC_INDEX), fabricIndex)
      endStructure()
    }
  }

  companion object {
    private const val TAG_CCDID = 0
    private const val TAG_CLIENT_CERTIFICATE = 1
    private const val TAG_INTERMEDIATE_CERTIFICATES = 2
    private const val TAG_FABRIC_INDEX = 254

    fun fromTlv(
      tlvTag: Tag,
      tlvReader: TlvReader,
    ): TlsCertificateManagementClusterTLSClientCertificateDetailStruct {
      tlvReader.enterStructure(tlvTag)
      val ccdid = tlvReader.getUShort(ContextSpecificTag(TAG_CCDID))
      val clientCertificate =
        if (!tlvReader.isNull()) {
          if (tlvReader.isNextTag(ContextSpecificTag(TAG_CLIENT_CERTIFICATE))) {
            Optional.of(tlvReader.getByteArray(ContextSpecificTag(TAG_CLIENT_CERTIFICATE)))
          } else {
            Optional.empty()
          }
        } else {
          tlvReader.getNull(ContextSpecificTag(TAG_CLIENT_CERTIFICATE))
          null
        }
      val intermediateCertificates =
        if (tlvReader.isNextTag(ContextSpecificTag(TAG_INTERMEDIATE_CERTIFICATES))) {
          Optional.of(
            buildList<ByteArray> {
              tlvReader.enterArray(ContextSpecificTag(TAG_INTERMEDIATE_CERTIFICATES))
              while (!tlvReader.isEndOfContainer()) {
                add(tlvReader.getByteArray(AnonymousTag))
              }
              tlvReader.exitContainer()
            }
          )
        } else {
          Optional.empty()
        }
      val fabricIndex = tlvReader.getUByte(ContextSpecificTag(TAG_FABRIC_INDEX))

      tlvReader.exitContainer()

      return TlsCertificateManagementClusterTLSClientCertificateDetailStruct(
        ccdid,
        clientCertificate,
        intermediateCertificates,
        fabricIndex,
      )
    }
  }
}
